<template>
  <div class="role-form">
    <h2>{{ isEditing ? '编辑角色' : '添加角色' }}</h2>
    <form @submit.prevent="handleSubmit">
      <div class="form-group">
        <label for="roleName">角色名称:</label>
        <input id="roleName" v-model="form.name" type="text" required>
      </div>
      <div class="form-group">
        <label for="roleDescription">角色描述:</label>
        <textarea id="roleDescription" v-model="form.description" required></textarea>
      </div>
      <button type="submit">{{ isEditing ? '更新' : '创建' }}</button>
      <button type="button" @click="handleCancel">取消</button>
    </form>
  </div>
</template>

<script>
import roleService from '@/src/services/roleService';

export default {
  props: {
    roleId: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      form: {
        name: '',
        description: ''
      },
      isEditing: false
    };
  },
  created() {
    if (this.roleId) {
      this.isEditing = true;
      this.loadRole();
    }
  },
  methods: {
    loadRole() {
      roleService.getRole(this.roleId).then(response => {
        this.form = response.data;
      }).catch(error => {
        alert('加载角色数据失败');
        console.error('Error:', error);
      });
    },
    handleSubmit() {
      const action = this.isEditing ? roleService.updateRole(this.roleId, this.form) : roleService.createRole(this.form);
      action.then(() => {
        this.$emit('formSubmitted');
        alert(`角色已${this.isEditing ? '更新' : '创建'}`);
      }).catch(error => {
        alert('操作失败');
        console.error('Error:', error);
      });
    },
    handleCancel() {
      this.$emit('formCanceled');
    }
  }
};
</script>

<style scoped>
.form-group {
  margin-bottom: 1em;
}
label {
  display: block;
  margin-bottom: 0.5em;
}
input[type="text"],
textarea {
  width: 100%;
  padding: 0.8em;
}
button {
  margin-right: 1em;
}
</style>
